<?php
class Pageley_Basic_Command_Save extends Pageley_Controller_Command_TransactionalReadWrite {
	protected function executeInternal() {
		$unitOfWork = $this->getUnitOfWork();
        $factory = Pageley_Config::getInstance();
		$type = $factory->valueOf("type." . $this->get("typeName"));
        $model = new Pageley_Util_ArrayMap();
        $entity = null;
        $serializer = Pageley_Serializer_Format::$HTTP->getSerializer();
        $id = $this->get("id");
        $prefix = $this->getProperties()->get("prefix");
        if($prefix === null) {
            $prefix = "";
        }
        try {
            if($id != null) {
                $entity = $unitOfWork->find($type, $id);
                $model->put("entity", $entity);
                if($entity === null) {
                    throw new Pageley_Controller_RuntimeException("Cannot update entity. Entity with id " . $id . " does not exist.");
                }
                $serializer->deserializeInto($this->getProperties(), $entity, $prefix);
            } else {
                $entity = $serializer->deserialize($this->getProperties(), $type, $prefix);
            }
            $model->put("entity", $entity);
        } catch(Pageley_Domain_Exception $e) {
            throw new Pageley_Controller_Exception("Command execution failed.", 0, $e, $this->getFailureAction(), $model);
        }
        $unitOfWork->register($entity);
		return new Pageley_Controller_ModelAndView($model);
	}
}